package ps

import (
	"fmt"
	influx "github.com/influxdata/influxdb1-client/v2"
	"github.com/shirou/gopsutil/v3/mem"
	"github.com/sirupsen/logrus"
	"log"
	"time"
	"tym.com/LogCollection/influxdb"
)

// MemInfo 内存结构体
type MemoryInfo struct {
	Total       uint64  `json:"total"`
	Available   uint64  `json:"available"`
	Used        uint64  `json:"used"`
	UsedPercent float64 `json:"used_percent"`
	Buffers     uint64  `json:"buffers"`
	Cached      uint64  `json:"cached"`
}

func getCurrentMemory() {

	info, err := mem.VirtualMemory()
	if err != nil {
		fmt.Printf("get mem info failed, err:%v", err)
		return
	}
	memInfo := MemoryInfo{
		Total:       info.Total,
		Available:   info.Available,
		Used:        info.Used,
		UsedPercent: info.UsedPercent,
		Buffers:     info.Buffers,
		Cached:      info.Cached,
	}

	packMemoryPoints(&memInfo)
}

func packMemoryPoints(mem *MemoryInfo) {
	monitorPoints, err := influx.NewBatchPoints(influx.BatchPointsConfig{
		Database:  "monitor",
		Precision: "s", //精度，默认ns
	})
	if err != nil {
		logrus.Error("influx: point fails!", err)
		return
	}
	tags := map[string]string{"mem": "curMemory"}
	fields := map[string]interface{}{
		"total":        int64(mem.Total),
		"available":    int64(mem.Available),
		"used":         int64(mem.Used),
		"used_percent": mem.UsedPercent,
	}

	pt, err := influx.NewPoint("memory", tags, fields, time.Now())
	if err != nil {
		log.Fatal(err)
	}
	monitorPoints.AddPoint(pt)
	influxdb.PointsSubChan <- monitorPoints
	logrus.Info("ps: insert influx memory")
}
